<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-16 20:40:08
 * @LastEditTime: 2019-12-13 13:49:56
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" href="../script/layim/dist/css/layui.mobile.css">
    <link rel="stylesheet" type="text/css" href="../css/longPressRecording.css">
    <!-- <link rel="stylesheet" type="text/css" href="../css/vant.css"> -->
    <link rel="stylesheet" type="text/css" href="../css/base.css" />
    <script type="text/javascript" src="../script/jquery.js"></script>
    <script type="text/javascript" src="../script/layer/mobile/layer.js"></script>
    <script type="text/javascript" src="../script/layim/dist/layui.js"></script>
    <script type="text/javascript" src="../script/jquery.signalR-2.4.1.min.js"></script>
    <script type="text/javascript" src="http://106.15.33.39:9981/signalr/hubs"></script>
    <script type="text/javascript" src="../script/signalr-mediate.js"></script>
    <!-- <script type="text/javascript" src="../script/vue.min.js"></script> -->
    <!-- <script type="text/javascript" src="../script/vant.min.js"></script> -->
    <!-- <script type="text/javascript" src="../script/fastclick.js"></script> -->
    <script type="text/javascript" src="../script/base.js"></script>
    <style type="text/css">
        html {
            background: #fff;
        }

        .layim-title {
            height: 40px !important;
            padding-top: 25px !important;
            line-height: 40px !important;
            /* text-align: center; */
            font-size: 16px !important;
        }

        .layui-layim {
            top: 65px !important;
            bottom: 0 !important;
        }

        .layim-chat-detail {
            top: 25px !important;
        }

        .layim-chat-main,
        .layim-content {
            top: 65px !important;
        }

        .layui-layim-tab {
            display: none;
        }

        .mp3_icon {
            display: inline-block;
            width: 32px;
            height: 22px;
            background: url(../image/play.png) no-repeat;
            background-size: 22px 22px;
            vertical-align: middle;
        }

        .chatlog-record {
            font-size: 16px;
        }

        /* .layui-layim-list li p{
            visibility: hidden;
        } */
    </style>
</head>

<body>
    <div layim-event="send" class="selfSend">1</div>
    <textarea title="消息模版" id="LAY_tpl" style="display:none;">

        <div class="layim-chat-main" style="overflow-y: auto;position: relative;height:100%;top:2px!important;">
            <ul>
                {{# layui.each(d.data, function(index, item){
                    if(item.id == $.layim.cache().mine.id){ }}
                      <li class="layim-chat-li layim-chat-mine"><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite><i>{{ layui.data.date(item.timestamp) }}</i>{{ item.username }}</cite></div><div class="layim-chat-text">{{ $.layim.content(item.content) }}</div></li>
                    {{# } else { }}
                      <li class="layim-chat-li"><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite>{{ item.username }}<i>{{ layui.data.date(item.timestamp) }}</i></cite></div><div class="layim-chat-text">{{ $.layim.content(item.content) }}</div></li>
                    {{# }
                  }); }}
            </ul>
        </div>

        
        </textarea>
    <div class="blackBoxSpeak">
        <p class="blackBoxSpeakConent">手指上划，取消发送</p>
    </div>

    <div class="blackBoxPause">
        <p class="blackBoxPauseContent" style="background: red">松开手指， 取消发送</p>
    </div>
</body>

<script type="text/javascript">
    var vm, nowChatData, userData, recMp3, audioStreamer, userContextIDs, nowPlayMp3, isRecord = false, isFirstTime = false;
    apiready = function () {

        recMp3 = api.require('recMp3');
        audioStreamer = api.require('audioStreamer');
        var changeHeadImg = function (headImg) {
            if (!headImg) {
                return "../image/header.png";
            }
            else {
                return headImg;
            }
        }
        $.clientCallBacks = {};
        var signalRHelper = function () {
            $.signalrApi({
                serverUrl: "http://" + FLD.serverIP,
                clientHub: "IMHub",
                clientEvents: [
                    {
                        name: "onClientConnect",
                        method: function (data) {
                            $.clientCallBacks["onClientConnect"](data);
                        }
                    },
                    {
                        name: "onChatMsg",
                        method: function (userId, msg, timestap) {
                            $.clientCallBacks["onChatMsg"](userId, msg, timestap);
                        }
                    },
                    {
                        name: "onGroupMsg",
                        method: function (userId, groupId, msg, timestap) {
                            $.clientCallBacks["onGroupMsg"](userId, groupId, msg, timestap);
                        }
                    },
                    {
                        name: "onUserOnlineNotify",
                        method: function (userInfo) {
                            $.clientCallBacks["onUserOnlineNotify"](userInfo);
                        }
                    },
                    {
                        name: "onUserOfflineNotify",
                        method: function (userId) {
                            $.clientCallBacks["onUserOfflineNotify"](userId);
                        }
                    }
                ]
            });
            //socket连接
            function signalrConnect() {
                $.signalrApi.start(function () {
                    var userInfo = FLD.getUserInfo();
                    $.signalrApi.server.clientConnect(userInfo.UserID);
                });
            }
            signalrConnect();

            setInterval(function () {

                try {
                    $.signalrApi.server.clientLive();
                } catch (e) {
                    $.signalrApi.start(function () {
                        var userInfo = FLD.getUserInfo();
                        $.signalrApi.server.clientConnect(userInfo.UserID);
                    });
                }

            }, 2000);
        }





        function layimInit() {

            setTimeout(function () {
                var html = '<span id="friends" style="float: right;" onclick="openFriends()"><i class="layui-icon" style="font-size:20px;">&#xe612;</i></span>'
                $('.layim-title p').append(html);
            }, 1000)

            var laytpl;

            layui.use('laytpl', function () {
                laytpl = layui.laytpl;
            })

            layui.config({
                version: true
            }).use('mobile', function () {
                var mobile = layui.mobile, layim = mobile.layim;
                $.layim = layim;


                setTimeout(function () {
                    setDIV_HTML()
                }, 500)


                FLD.ajax('GetChatUser', {}, function (res) {
                    userData = res.ds[0];
                    var mine = {
                        username: res.ds[0].UserName,
                        id: res.ds[0].UserID.toString(),
                        status: "online",
                        sign: res.ds[0].Sign,
                        avatar: changeHeadImg(res.ds[0].HeadImg)
                    }
                    var friendInfo = [{
                        "groupname": "福路德用户",
                        id: 1
                    }];

                    var groups = [];
                    friend = [];
                    //用户列表
                    for (var i = 0; i < res.ds1.length; i++) {
                        friend.push({
                            username: res.ds1[i].UserName,
                            id: res.ds1[i].UserID.toString(),
                            status: res.ds1[i].ContextIDs ? "online" : 'offline',
                            sign: res.ds1[i].Sign,
                            avatar: changeHeadImg(res.ds1[i].HeadImg),
                            contextIDs: res.ds1[i].ContextIDs
                        })
                    }
                    //群列表
                    for (var i = 0; i < res.ds2.length; i++) {
                        groups.push({
                            groupname: res.ds2[i].GroupName,
                            id: res.ds2[i].GroupID,
                            avatar: "../image/group.png" //群组头像
                        })
                    }

                    friendInfo[0].list = friend;

                    $.clientCallBacks["onClientConnect"] = (contextID) => {
                        userContextIDs = contextID;
                        mine["contextIDs"] = contextID;
                    }
                    $.clientCallBacks["onChatMsg"] = (userId, msg, timestamp) => {
                        let fs = friend.filter(item => item.id == userId);
                        if (fs.length > 0) {
                            //接收消息
                            layim.getMessage({
                                username: fs[0].username
                                , avatar: fs[0].avatar
                                , id: fs[0].id
                                , type: "friend" //聊天窗口来源类型，从发送消息传递的to里面获取
                                , content: msg
                                , cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                                , mine: false //是否我发送的消息，如果为true，则会显示在右方
                                , fromid: fs[0].id //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                , timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                            });
                            setDIV_HTML();
                            setTimeout(function () {
                                if ($(".layim-chat-main").length > 0) {
                                    //更新最后阅读时间
                                    FLD.ajax('UpdateReaderTime', {}, function () {

                                    })
                                } else {
                                    api.sendEvent({
                                        name: 'setUnRedMsg',
                                        extra: {
                                            dot: true
                                        }
                                    });
                                }
                            }, 0);

                        }
                    }
                    $.clientCallBacks["onGroupMsg"] = (userId, groupId, msg, timestamp) => {
                        let fs = friend.filter(item => item.id == userId);
                        if (fs.length > 0) {
                            //接收消息
                            layim.getMessage({
                                username: fs[0].username
                                , avatar: fs[0].avatar
                                , id: groupId
                                , type: "group" //聊天窗口来源类型，从发送消息传递的to里面获取
                                , content: msg
                                , cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                                , mine: false //是否我发送的消息，如果为true，则会显示在右方
                                , fromid: fs[0].id //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                , timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                            });
                            setDIV_HTML();
                            setTimeout(function () {
                                if ($(".layim-chat-main").length > 0) {
                                    //更新最后阅读时间
                                    FLD.ajax('UpdateReaderTime', {}, function () {

                                    })
                                } else {
                                    api.sendEvent({
                                        name: 'setUnRedMsg',
                                        extra: {
                                            dot: true
                                        }
                                    });
                                }
                            }, 0);
                        }

                    }


                    $.clientCallBacks["onUserOnlineNotify"] = (info) => {
                        let userInfo = JSON.parse(info);
                        if (friend.filter(item => item.id.toString() == userInfo.UserID.toString()).length > 0) {
                            layim.setFriendStatus(userInfo.UserID.toString(), 'online');
                        }
                        else {
                            //如果用户不存在，则把该用户加入好友圈
                            layim.addList({
                                type: 'friend'
                                , avatar: changeHeadImg(userInfo.HeadImg)
                                , username: userInfo.UserName
                                , groupid: 1 //所在的分组id
                                , id: userInfo.UserID.toString()
                                , sign: userInfo.Sign
                            });
                            layim.setFriendStatus(userInfo.UserID.toString(), 'online');
                        }
                    }
                    $.clientCallBacks["onUserOfflineNotify"] = (userId) => {
                        layim.setFriendStatus(userId.toString(), 'offline');
                    }

                    signalRHelper();

                    layim.config({
                        chatTitleColor: '#cd1b21',
                        members: {
                            url: "http://" + FLD.serverIP + '/Frame/ST1_FLD/Handler.aspx?cmd=getMembers', //接口地址
                            type: 'post' //默认get，一般可不填
                        },
                        //上传图片接口
                        uploadImage: {
                            url: "http://" + FLD.serverIP + '/Frame/ST1_FLD/Handler.aspx?cmd=chatUploadImg', //（返回的数据格式见下文）
                            type: 'post' //默认post
                        },

                        //上传文件接口
                        uploadFile: {
                            url: "http://" + FLD.serverIP + '/Frame/ST1_FLD/Handler.aspx?cmd=chatUploadFile', //（返回的数据格式见下文）
                            type: 'post' //默认post
                        },
                        chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html', //聊天记录页面地址，若不开启，剔除该项即可
                        init: {
                            //我的信息
                            mine: mine,
                            //我的好友列表
                            friend: friendInfo,
                            //群组
                            group: groups
                        },
                        isNewFriend: false,
                        isgroup: true, //是否开启“群聊”,
                        title: '最近消息', //应用名，默认：我的IM
                        tool: [{
                            alias: 'chatlog' //工具别名
                            , title: 'chatlog' //工具名称
                            , iconUnicode: '&#xe63c;'
                            , iconClass: 'chatlog-record'
                        }]
                    });

                    //创建一个会话

                    layim.on('chatChange', function (data) {
                        nowChatData = data;
                        nowPlayMp3 = '';
                        isFirstTime = true;
                        setTimeout(function () {
                            isFirstTime = false;
                        }, 1500)
                        api.setFrameAttr({
                            name: 'chat',
                            rect: {
                                x: 0,
                                y: 0,
                                w: api.winWidth,
                                h: api.winHeight
                            },
                        });
                        setTimeout(function () {
                            showAudioImg();
                            var scroll = $('.layim-chat-main')[0].scrollHeight - $('.layim-chat-main').height() - 10;
                            $('.layim-chat-main').scrollTop(scroll)
                        }, 1000)
                        //更新最后阅读时间
                        FLD.ajax('UpdateReaderTime', {}, function () {

                        })
                    });

                    //监听返回
                    layim.on('back', function () {
                        //如果你只是弹出一个会话界面（不显示主面板），那么可通过监听返回，跳转到上一页面，如：history.back();

                        audioStreamer.stop();
                        if (!isRecord) {
                            api.setFrameAttr({
                                name: 'chat',
                                rect: {
                                    x: 0,
                                    y: 0,
                                    w: api.winWidth,
                                    h: api.winHeight - 61 - api.safeArea.bottom
                                },
                            });
                        }
                        isRecord = false;
                        //更新最后阅读时间
                        FLD.ajax('UpdateReaderTime', {}, function () {
                            FLD.ajax('getUnReadMsg', {}, function (res) {
                                if (res.ds.length > 0 || res.ds1.length > 0) {
                                    api.sendEvent({
                                        name: 'setUnRedMsg',
                                        extra: {
                                            dot: true
                                        }
                                    });
                                } else {
                                    api.sendEvent({
                                        name: 'setUnRedMsg',
                                        extra: {
                                            dot: false
                                        }
                                    });
                                }
                            })
                        })
                    });
                    //监听自定义工具栏点击，以上述扩展的工具为例
                    layim.on('tool(chatlog)', function (insert, send, obj) { //事件中的tool为固定字符，而code则为过滤器，对应的是工具别名（alias）
                        isRecord = true;
                        if (nowChatData.data.type == 'friend') {
                            var obj = {
                                fromUserID: FLD.getUserInfo().UserID,
                                toUserID: nowChatData.data.id
                            }
                            FLD.ajax('GetUserChatHistory', obj, function (res) {
                                let history = [];
                                for (var i = 0; i < res.ds.length; i++) {
                                    history.push({
                                        username: res.ds[i].UserName,
                                        id: res.ds[i].FromUserID,
                                        avatar: changeHeadImg(res.ds[i].HeadImg),
                                        timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000,
                                        content: res.ds[i].Content
                                    })
                                }
                                var html = laytpl(LAY_tpl.value).render({
                                    data: history
                                });
                                isFirstTime = true;
                                setTimeout(function () {
                                    isFirstTime = false;
                                }, 1500)
                                //弹出一个更多聊天记录面板
                                layim.panel({
                                    title: '与 ' + nowChatData.data.username + ' 的聊天记录',
                                    tpl: html,
                                    data: {
                                        data: history
                                    }
                                });
                                $('.layim-chat-main').scrollTop(99999999999999)
                            })


                        } else {
                            var obj = {
                                GroupID: nowChatData.data.id
                            }
                            FLD.ajax('GetGroupChatHistory', obj, function (res) {
                                let history = [];
                                for (var i = 0; i < res.ds.length; i++) {
                                    history.push({
                                        username: res.ds[i].UserName,
                                        id: res.ds[i].FromUserID,
                                        avatar: changeHeadImg(res.ds[i].HeadImg),
                                        timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000,
                                        content: res.ds[i].Content
                                    })
                                }
                                var html = laytpl(LAY_tpl.value).render({
                                    data: history
                                });
                                isFirstTime = true;
                                setTimeout(function () {
                                    isFirstTime = false;
                                }, 1500)
                                //弹出一个更多聊天记录面板
                                layim.panel({
                                    title: '与 ' + nowChatData.data.username + ' 的聊天记录',
                                    tpl: html,
                                    data: {
                                        data: history
                                    }
                                });
                                $('.layim-chat-main').scrollTop(99999999999999)
                            })
                        }


                    });
                    //监听发送消息
                    layim.on('sendMessage', function (res) {
                        let fromContextID = mine.contextIDs;
                        let fromUserID = mine.id;
                        let toUserID = res.to.id;
                        let msg = res.mine.content;
                        let sendType = res.to.type;
                        if (sendType == 'friend') {
                            $.signalrApi.server.chatMsg(fromContextID, fromUserID, toUserID, msg);
                        }
                        else {
                            $.signalrApi.server.groupMsg(fromContextID, fromUserID, toUserID, msg);
                        }
                        //更新最后阅读时间
                        FLD.ajax('UpdateReaderTime', {}, function () {
                            setDIV_HTML();
                        })
                    });
                    //获取未读信息
                    setTimeout(function () {
                        FLD.ajax('getUnReadMsg', {}, function (res) {
                            if (res.ds.length > 0 || res.ds1.length > 0) {
                                api.sendEvent({
                                    name: 'setUnRedMsg',
                                    extra: {
                                        dot: true
                                    }
                                });
                            }
                            for (var i = 0; i < res.ds.length; i++) {
                                //每条消息重新发送给当前用户
                                let fs = friend.filter(item => item.id == res.ds[i].FromUserID);
                                if (fs.length > 0) {
                                    //接收消息
                                    layim.getMessage({
                                        username: fs[0].username
                                        , avatar: fs[0].avatar
                                        , id: fs[0].id
                                        , type: "friend" //聊天窗口来源类型，从发送消息传递的to里面获取
                                        , content: res.ds[i].Content
                                        , cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                                        , mine: false //是否我发送的消息，如果为true，则会显示在右方
                                        , fromid: fs[0].id //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                        , timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                                    });
                                    // document.getElementById('msg_mp3').play();
                                }
                            }
                            for (var i = 0; i < res.ds1.length; i++) {
                                let fs = friend.filter(item => item.id == res.ds1[i].FromUserID);
                                if (fs.length > 0) {
                                    //接收消息
                                    layim.getMessage({
                                        username: fs[0].username
                                        , avatar: fs[0].avatar
                                        , id: res.ds1[i].GroupID
                                        , type: "group" //聊天窗口来源类型，从发送消息传递的to里面获取
                                        , content: res.ds1[i].Content
                                        , cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                                        , mine: false //是否我发送的消息，如果为true，则会显示在右方
                                        , fromid: fs[0].id //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                        , timestamp: res.ds1[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                                    });
                                    // document.getElementById('msg_mp3').play();
                                }
                            }
                            setTimeout(function () {
                                setDIV_HTML();
                            }, 500)
                        })
                    }, 3000);
                })
            });
        }
        layimInit();
    }

    $(function () {
        setTimeout(function () {

            $('.layui-layim').scroll(function () {
                if ($('.layui-layim').scrollTop() == 0) {
                    $('.layui-layim').scrollTop(1)
                }
                if ($('.layui-layim').scrollTop() == ($('.layui-layim')[0].scrollHeight) - $('.layui-layim').height()) {
                    $('.layui-layim').scrollTop($('.layui-layim')[0].scrollHeight - $('.layui-layim').height() - 1)
                }
            })

        }, 1000)

    })


    function setDIV_HTML() {
        $('.layui-layim-list li p').each(function () {
            if ($(this).html().indexOf('div') > -1) {
                if ($(this).html().indexOf('mp3_src') > -1) {
                    $(this).html('[语音消息]')
                } else {
                    $(this).html('[推送消息]')
                }
            }
        })
    }

    function openDetailFromMsg(that) {
        if (isFirstTime) {
            return false;
        }
        var S_BillType = parseInt($(that).find('.b-t').attr('S_BillType'))
        var S_BillID = parseInt($(that).find('.b-t').attr('S_BillID'))
        var obj = {
            S_BillType: S_BillType,
            S_BillID: S_BillID
        }
        FLD.ajax('AP_HisList_XX', obj, function (res) {
            if (res.ds.length) {
                var row = res.ds[0];
                
                if (S_BillType == 101 || S_BillType == 1101) {
                    if (row.B_Type == 3) {
                        api.openWin({
                            name: 'sellingPrint',
                            url: 'sellingPrint.html',
                            reload: true,
                            slidBackEnabled: false,
                            pageParam: {
                                historyData: row
                            }
                        })
                    } else {
                        api.openWin({
                            name: 'selling',
                            url: 'selling.html',
                            reload: true,
                            slidBackEnabled: false,
                            pageParam: {
                                historyData: row
                            }
                        })
                    }
                } else if (S_BillType == 401) {
                    api.openWin({
                        name: 'receipt',
                        url: 'receipt.html',
                        reload: true,
                        slidBackEnabled: false,
                        pageParam: {
                            historyData: row
                        }
                    })
                }
            }
        })



    }

    function back() {
        $('.layim-tab-content').removeClass('layui-show');
        $('.layim-tab-content').eq(0).addClass('layui-show');
        $('.layui-layim').scrollTop(1);
        $('#friends').show();
        $('#back').hide();

    }

    function openFriends() {
        $('.layim-tab-content').removeClass('layui-show');
        $('.layim-tab-content').eq(1).addClass('layui-show');
        $('.layui-layim').scrollTop(1);
        $('#friends').hide();
        if ($('#back').length) {
            $('#back').show();
        } else {
            var i_html = '<i class="layui-icon layim-chat-back" id="back" onclick="back()">&#xe603;</i>'
            $('.layim-title p').prepend(i_html);
        }
    }

    function toggleOutput() {
        var imgsrc = $('#inputType').attr('src');
        if (imgsrc.indexOf('audio') > -1) {
            $('#inputType').attr('src', '../image/keyboard.png')
            $('#writeInput').hide();
            $('#audioInput').show();
            $('#sendButton').hide();
        } else {
            $('#inputType').attr('src', '../image/audio.png')
            $('#writeInput').show();
            $('#audioInput').hide();
            $('#sendButton').show();
        }

    }

    function playmp3(that) {
        if (isFirstTime) {
            return false;
        }
        $('.mp3_icon').css({
            'background': 'url(../image/play.png) no-repeat',
            'background-size': '22px 22px'
        })


        audioStreamer.onNormal();
        // audioStreamer.setVolume({  
        //     volume: 1
        // });
        if (nowPlayMp3 == $(that).attr('mp3_src')) {
            audioStreamer.stop();
            nowPlayMp3 = '';
        } else {
            $(that).find('.mp3_icon').css({
                'background': 'url(../image/stop.png) no-repeat',
                'background-size': '22px 22px'
            })
            audioStreamer.openPlayer({
                path: $(that).attr('mp3_src'),
            }, function (ret) {

            });
            nowPlayMp3 = $(that).attr('mp3_src');
        }


        audioStreamer.addEventListener({
        }, function (ret) {
            if (ret.state == 'finished') {
                nowPlayMp3 = '';
                $('.mp3_icon').css({
                    'background': 'url(../image/play.png) no-repeat',
                    'background-size': '22px 22px'
                })
            }
        });
    }

    function showAudioImg() {
        //录音按钮
        var audioInput = document.getElementById("audioInput");

        //中间黑色边框和里面的内容（录音状态）
        var blackBoxSpeak = document.querySelector(".blackBoxSpeak");
        blackBoxSpeak.style.background = "url('../image/ic_record@2x.png')no-repeat 28 16px/65px 104px, url('../image/ic_record_ripple@2x-9.png')no-repeat 111.2px 32px/28.8px 88px";
        blackBoxSpeak.style.backgroundColor = "rgba(0,0,0,.7)";

        //中间黑色边框和里面的内容（暂停状态）
        var blackBoxPause = document.querySelector(".blackBoxPause");
        blackBoxPause.style.background = "rgba(0,0,0,.7) url('../image/ic_release_to_cancel@2x.png')no-repeat center 8px/67.2px 104px";
        blackBoxPause.style.backgroundColor = "rgba(0,0,0,.7)";

        //手指移动相关
        var posStart = 0; //初始化起点坐标
        var posEnd = 0; //初始化终点坐标
        var posMove = 0; //初始化滑动坐标

        //轮播相关
        var index = [9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        var num = index.length;
        var timer = null; //用于清除计时器

        function initEvent() {
            audioInput.addEventListener("touchstart", function (event) {
                setTimer();
                event.preventDefault(); //阻止浏览器默认行为
                posStart = 0;
                posStart = event.touches[0].pageY; //获取起点坐标


                recMp3.start(function (ret, err) {
                    if (ret) {
                        if (ret.db != undefined) {
                            // 在这里做ui 处理 
                        } else {
                            //打开成功，开始录音
                        }
                    }
                });
                //显示录音 隐藏暂停
                showBlackBoxSpeak();

            });
            audioInput.addEventListener("touchmove", function (event) {
                event.preventDefault(); //阻止浏览器默认行为

                posMove = event.targetTouches[0].pageY; //获取滑动实时坐标
                if (posStart - posMove < 200) {
                    //隐藏录音 显示暂停
                    showBlackBoxSpeak();
                } else {
                    //显示录音 隐藏暂停
                    showBlackBoxPause();
                }
            });
            audioInput.addEventListener("touchend", function (event) {
                event.preventDefault(); //阻止浏览器默认行为
                posEnd = 0;
                posEnd = event.changedTouches[0].pageY; //获取终点坐标

                clearInterval(timer);
                //初始化状态
                initStatus();

                if (posStart - posEnd < 200) {
                    //发送成功
                    showBlackBoxNone();
                    setTimeout(function () {
                        recMp3.stop(function (ret, err) {
                            if (ret) {
                                var path = ret.path;
                                if (!path) {
                                    // layer.open({
                                    //     content: '您未发出声音 请重新尝试!',
                                    //     skin: 'msg',
                                    //     time: 2
                                    // });
                                } else {
                                    FLD.uploadFile('APP_Audio', path, function (path) {
                                        var mp3_path = 'http://' + FLD.serverIP + path;
                                        var msgHtml = '[div mp3_src=' + mp3_path + ' onclick=playmp3(this)][div class=mp3_icon][/div][div style=display:inline-block;vertical-align: middle; ]语音消息[/div][/div]'
                                        $('#writeInput').val(msgHtml);
                                        $('.selfSend').click();
                                    })
                                }

                            }
                        });
                    }, 1000)


                } else {
                    //取消发送
                    showBlackBoxNone();

                    recMp3.stop(function (ret, err) {

                    });
                }
            });
        }

        initEvent();

        //轮播
        function setTimer() {
            // timer = setInterval(function () {
            //     setTimeout(function () {
            //         num++;
            //         blackBoxSpeak.style.background = "url('../image/ic_record@2x.png')no-repeat 28px 16px/64px 104px, url('../image/ic_record_ripple@2x-" + index[num] + ".png')no-repeat 111.2px 32px/28.8px 88px";
            //         blackBoxSpeak.style.backgroundColor = " rgba(0,0,0,.7)";
            //     }, 70);
            //     if (num >= index.length - 1) {
            //         num = 0;
            //     }
            // }, 200);

            blackBoxSpeak.style.background = "url('../image/ic_record@2x.png')no-repeat 28px 16px/64px 104px, url('../image/ic_record_ripple@2x-" + index[2] + ".png')no-repeat 111.2px 32px/28.8px 88px";
            blackBoxSpeak.style.backgroundColor = " rgba(0,0,0,.7)";
        }

        //初始化状态
        var initStatus = function () {
            audioInput.value = '按住 说话';
            //全部隐藏
            showBlackBoxNone();
        }

        //显示录音 隐藏暂停
        var showBlackBoxSpeak = function () {
            audioInput.value = '松开 结束';
            blackBoxSpeak.style.display = "block";
            blackBoxPause.style.display = "none";
        }

        //隐藏录音 显示暂停
        var showBlackBoxPause = function () {
            audioInput.value = '松开手指，取消发送';
            blackBoxSpeak.style.display = "none";
            blackBoxPause.style.display = "block";
        }

        //隐藏录音
        var showBlackBoxNone = function () {
            blackBoxSpeak.style.display = "none";
            blackBoxPause.style.display = "none";
        }
    }
</script>

</html>